package com.wmlive.hhvideo.application;

import android.app.Activity;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDexApplication;

import com.bugtags.library.Bugtags;
import com.bugtags.library.BugtagsOptions;
import com.dyuiapi.api.DyUIAPI;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.stetho.Stetho;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.wmlive.hhvideo.broadcastreceiver.NetWorkStatusReceiver;
import com.wmlive.hhvideo.common.AppCacheFileUtils;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.MyAppActivityManager;
import com.wmlive.hhvideo.common.network.DCRequest;
import com.wmlive.hhvideo.dcijkplayerlib.DcIjkPlayerManager;
import com.wmlive.hhvideo.heihei.recordvideo.DyUIAPICallbackImpl;
import com.wmlive.hhvideo.heihei.recordvideo.fragment.PublishVideoFragmentImpl;
import com.wmlive.hhvideo.heihei.websocket.WebSocketServiceManager;
import com.wmlive.hhvideo.jpush.JpushReceiver;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.TaskUtils;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.WeakHandler;
import com.wmlive.hhvideo.utils.preferences.SPUtils;

import java.io.File;

import cn.jpush.android.api.JPushInterface;
import cn.wmlive.hhvideo.BuildConfig;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Applicatioin
 * Created by vhawk on 2017/5/22.
 * Modify by lsq
 */

public class DCApplication extends MultiDexApplication implements Handler.Callback {

    private static final int TYPE_EXIT = 100;

    private static DCApplication sContext;

    private WeakHandler weakHandler;

    private static File cacheRecordVideoFile;//第三方的视频缓存目录

    private Activity currentActivity;  //当前Activity
    private NetWorkStatusReceiver netWorkStateReceiver;


    @Override
    public void onCreate() {
        super.onCreate();

        //如果app存在多进程，Application的onCreate()会执行多次
        if (BuildConfig.APPLICATION_ID.equals(TaskUtils.getCurrentProcessName(this))) {
            sContext = this;

            initBugtags();

            LeakCanary.install(this); //内存泄漏分析

            CrashReport.initCrashReport(getApplicationContext(), "9d068ada48", GlobalParams.Config.IS_DEBUG);

            //初始化Log
            KLog.init(GlobalParams.Config.IS_DEBUG, GlobalParams.Config.APP_LOG_TAG);

//            initUMengShareConfig();

            //初始化SharedPreferences
            SPUtils.init("dc_encrypt_key", "dc_preferences");

//            DcIjkPlayer.initPlayer();
            DcIjkPlayerManager.get().init(this);

            //初始化Toast
            ToastUtil.init(this);

            weakHandler = new WeakHandler(this);

            //初始化App的缓存文件夹
            initFileAndNetwork();

            //app 状态切换在API 14之后，在Application类中
            registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
            //录制
            initializeDyUIAPI();

            Stetho.initializeWithDefaults(this);
            registerNetStateReceiver();

            JPushInit();
        } else {
            //非嘿嘿的进程
            KLog.e("MyWebsocketService", TaskUtils.getCurrentProcessName(this) + "------------------");
        }
    }

    @Override
    public void onTerminate() {
        unregisterNetStateReceiver();
        super.onTerminate();
    }

    private void initFileAndNetwork() {
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(@NonNull Integer integer) throws Exception {
                        return AppCacheFileUtils.isAppCacheDirectoryInit(sContext);
                    }
                })
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (!aBoolean) {
                            KLog.i("初始化app缓存目录");
                            AppCacheFileUtils.initAppInternalCacheDirectory(sContext);
                            AppCacheFileUtils.initAppInternalFilesDirectory(sContext);
                            AppCacheFileUtils.initAppExternalDirectory();
                        }
                        //DCRequest.getInstance().initRetrofit(this, GlobalParams.Config.IS_DEBUG, FileUtil.getAppHttpCachePath());
                        DCRequest.getInstance().initRxJavaRetrofit(sContext, GlobalParams.Config.IS_DEBUG, AppCacheFileUtils.getAppHttpCachePath(), GlobalParams.Config.APP_LOG_TAG);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    private void initBugtags() {
        //在这里初始化BugTagst
        BugtagsOptions options = new BugtagsOptions.Builder().
                trackingLocation(true).       //是否获取位置，默认 true
                trackingCrashLog(false).       //是否收集闪退，默认 true
                trackingConsoleLog(false).     //是否收集控制台日志，默认 true
                trackingUserSteps(true).      //是否跟踪用户操作步骤，默认 true
                crashWithScreenshot(false).    //收集闪退是否附带截图，默认 true
                versionName(BuildConfig.VERSION_NAME).         //自定义版本名称，默认 app versionName
                versionCode(BuildConfig.VERSION_CODE).              //自定义版本号，默认 app versionCode
                trackingNetworkURLFilter("(.*)").//自定义网络请求跟踪的 url 规则，默认 null
                enableUserSignIn(true).            //是否允许显示用户登录按钮，默认 true
                startAsync(true).    //设置 为 true 则 SDK 会在异步线程初始化，节省主线程时间，默认 false
                startCallback(null).            //初始化成功回调，默认 null
                remoteConfigDataMode(Bugtags.BTGDataModeProduction).//设置远程配置数据模式，默认Bugtags.BTGDataModeProduction 参见[文档](https://docs.bugtags.com/zh/remoteconfig/android/index.html)
                remoteConfigCallback(null).//设置远程配置的回调函数，详见[文档](https://docs.bugtags.com/zh/remoteconfig/android/index.html)
                enableCapturePlus(false).        //是否开启手动截屏监控，默认 false，参见[文档](https://docs.bugtags.com/zh/faq/android/capture-plus.html)
                //extraOptions(key,value).                //设置 log 记录的行数，详见下文
                        build();
        if(GlobalParams.Config.IS_DEBUG){
            Bugtags.start("c18456ca0308f5040dfbd13912e97aa6", sContext, Bugtags.BTGInvocationEventBubble, options);
        }else{
            Bugtags.start("c18456ca0308f5040dfbd13912e97aa6", sContext, Bugtags.BTGInvocationEventNone, options);
        }
        //      Bugtags.BTGInvocationEventBubble,在app中显示圆形小球
        //      Bugtags.BTGInvocationEventNone,在app中不显示圆形小球
        //      Bugtags.BTGInvocationEventShake,通过摇一摇让圆形小球显示出来

    }

    public static DCApplication getDCApp() {
        return sContext;
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case TYPE_EXIT:
                weakHandler.removeCallbacksAndMessages(null);
                KLog.i("--退出App");
                MobclickAgent.onKillProcess(sContext);
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
        }
        return true;
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 完全退出App
     */
    public void exitApp() {
        if (null != weakHandler) {
            weakHandler.sendEmptyMessageDelayed(TYPE_EXIT, 600);
        }
        WebSocketServiceManager.getInstance(this).stopWebSocketService();
    }

    /**
     * 初始化录制
     *
     * @return
     */
    public boolean initializeDyUIAPI() {
        // 这里确定是否启用日志，在调试阶段可开启该选项，方便定位问题。打包为发行版时，此启用无效
        boolean autoDebuggable = GlobalParams.Config.IS_DEBUG;
        cacheRecordVideoFile = AppCacheFileUtils.getAppVideoRecordCachePathFile(this);
        try {
            //调用初始化
            DyUIAPI.initialize(this, cacheRecordVideoFile, PublishVideoFragmentImpl.class,
                    DyUIAPICallbackImpl.getInstance(), autoDebuggable, GlobalParams.RecordTime.minVideoDuration, GlobalParams.RecordTime.maxVideoDuratio);

            Fresco.shutDown();
            Fresco.initialize(this);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取音乐缓存文件
     *
     * @return
     */
    public static File getCacheRecordVideoFile() {
        return cacheRecordVideoFile;
    }


    /**
     * activity 各个状态切换
     */
    int count = 0;//监听是否在前台，限制极光推送

    public class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            MyAppActivityManager.getInstance().pushActivity(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {
            count = count + 1;
            if (count > 0) {
                if (null != JPushInterface.getRegistrationID(DCApplication.this)) {
                    JPushInterface.stopPush(getApplicationContext());
                }
            }
        }

        @Override
        public void onActivityResumed(Activity activity) {
            currentActivity = activity;
        }

        @Override
        public void onActivityPaused(Activity activity) {
            currentActivity = null;
        }

        @Override
        public void onActivityStopped(Activity activity) {
            count = count - 1;
            if (count <= 0) {
                JPushInterface.resumePush(getApplicationContext());
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            MyAppActivityManager.getInstance().popActivity(activity);
        }
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }


    private void registerNetStateReceiver() {
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStatusReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
    }


    private void unregisterNetStateReceiver() {
        unregisterReceiver(netWorkStateReceiver);
    }

    /**
     * 初始化JPush(极光)
     */
    private void JPushInit() {
        JPushInterface.setDebugMode(GlobalParams.Config.IS_DEBUG);
        JPushInterface.init(this);
//        JPushInterface.setLatestNotificationNumber(this, 3);
    }
}
